package org.jing.ext.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * Description: <br>
 *
 * @author bksmate <br>
 * @since 2024-12-24 <br>
 */
public class WebHeaders {
    private volatile Map<String, String> headers;

    public WebHeaders() {}

    public WebHeaders(Map<String, String> map) {
        if (null != map) {
            headers = new HashMap<>(map);
        }
    }

    private Map<String, String> getHeaders() {
        if (null == headers) {
            synchronized (this) {
                if (null == headers) {
                    headers = new HashMap<>();
                }
            }
        }
        return headers;
    }

    public void putAll(Map<String, List<String>> fields) {
        for (Map.Entry<String, List<String>> entry : fields.entrySet()) {
            if (null != entry.getKey()) {
                StringBuilder stbr = new StringBuilder();
                if (null != entry.getValue()) {
                    for (String val : entry.getValue()) {
                        if (stbr.length() > 0) {
                            stbr.append(" ,");
                        }
                        stbr.append(val);
                    }
                }
                getHeaders().put(entry.getKey(), stbr.toString());
            }
        }
    }

    public void set(String key, String value) {
        getHeaders().put(key, value);
    }

    public String get(String key) {
        return getHeaders().get(key);
    }

    public void remove(String key) {
        getHeaders().remove(key);
    }

    public void clear() {
        getHeaders().clear();
    }

    public void forEach(BiConsumer<String, String> consumer) {
        getHeaders().forEach(consumer);
    }

    @Override public String toString() {
        return getHeaders().toString();
    }
}
